from django.contrib import admin

from django.contrib.auth.admin import UserAdmin

from accounts.forms import UserProfileAdminForm
from accounts.models import User, UserProfile, UserAddress, LoginRecord, PasswdChangeLog

# Register your models here.
from utils.admin_actions import set_valid, set_invalid


@admin.register(User)
class UserAdmin(UserAdmin):
    """用户基础信息"""
    # fields = ('integral', 'level', 'nickname')
    list_display = ('format_username', 'nickname', 'integral', 'is_active')
    # 支持按用户名、昵称进行搜索
    search_fields = ('username', 'nickname')
    # 添加自定义方法
    actions = ['disable_user', 'enable_user']
    fieldsets = (
        (None, {'fields': ('username', 'password')}),
        (('Personal info'), {'fields': ('first_name', 'last_name', 'email', 'nickname', 'level', 'integral')}),
        (('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
                                       'groups', 'user_permissions')}),
        (('Important dates'), {'fields': ('last_login', 'date_joined')}),
    )
    list_per_page = 5

    def format_username(self, obj):
        """用户脱敏处理"""
        return obj.username[0:3] + '***'
    # 修改列名显示
    format_username.short_description = '用户名'

    def disable_user(self, request, queryset):
        """批量禁用选中的用户"""
        queryset.update(is_active=False)
    disable_user.short_description = '批量禁用用户'

    def enable_user(self, request, queryset):
        """批量禁用选中的用户"""
        queryset.update(is_active=True)
    enable_user.short_description = '批量启用用户'


# admin.site.register(User, UserAdmin)
@admin.register(UserProfile)
class UserProfileAdmin(admin.ModelAdmin):
    """用户详细信息"""
    list_display = ('user', 'phone_no', 'sex')
    list_per_page = 5
    # 自定义表单
    form = UserProfileAdminForm

@admin.register(UserAddress)
class UserAddressAdmin(admin.ModelAdmin):
    """用户地址管理"""
    list_display = ('user', 'province', 'city', 'username',
                    'address', 'phone', 'is_default', 'is_valid')
    search_fields = ('user__username', 'user__nickname'
                     'phone', 'username')
    list_per_page = 5

    actions = [set_valid, set_invalid]

@admin.register(LoginRecord)
class LoginRecordAdmin(admin.ModelAdmin):
    """用户的登陆历史"""
    list_display = ('user', 'username', 'ip', 'source')
    list_per_page = 5

@admin.register(PasswdChangeLog)
class PasswdChangeLogAdmin(admin.ModelAdmin):
    """用户密码修改历史"""
    list_display = ('user', 'phone_no', 'emial')
    list_per_page = 5
